const express = require('express');
const utils = require('utility');
const Router = express.Router();
const model = require('../db');
const User = model.getModel('user');
const Chat = model.getModel('chat');
const _filter = {'password': 0,'__v': 0};

function md5Pwd(pwd){
	const salt = 'hongshibao19950508BAO';
	return utils.md5(utils.md5(pwd + salt));
}

Router.get('/list', function(req, res) {
	const type = req.query.type;
	//User.remove({},function(e,d){})
    User.find({type}, function(err, doc){
        if (err) {
            return res.send('查询失败');
        }
		return res.json({
            code:0,
            data:doc
        });
	})
})

Router.post('/login', function(req,res){
	const {user, password} = req.body
	User.findOne({user, password: md5Pwd(password)}, _filter, function(err,doc){
		if (!doc) {
			return res.json({code: 1,msg: '用户名或者密码错误'});
		}
		res.cookie('userid', doc._id);
		return res.json({code: 0,data: doc});
	})
})

Router.post('/register', function(req, res){
	const {user, password, type} = req.body;
	User.findOne({user},function(err,doc){
		if (doc) {
			return res.json({code: 1,msg: '用户名重复'});
		}
		
		const userModel = new User({user, type, password: md5Pwd(password)});
		userModel.save(function(e, d){
			if (e) {
				return res.json({code: 1,msg: '后端出错了'});
			}
			const {user, type, _id} = d;
			res.cookie('userid', _id);
			return res.json({code: 0,data: {user, type, _id}});
		})
	})
})

Router.post('/update', function(req, res){
	const userid = req.cookies.userid;
	if (!userid) {
		return json.dumps({code: 1})
	}
	const body = req.body;
	User.findByIdAndUpdate(userid, body,function(err, doc){
		const data = Object.assign({},{
			user: doc.user,
			type: doc.type
		}, body)
		return res.json({code: 0, data});
	})
})

Router.get('/info',function(req, res){
	const userid = req.cookies.userid;
	if (!userid) {
		return res.json({code: 1});
	}
	User.findOne({_id: userid}, _filter, function(err,doc){
		if (err) {
			return res.json({code: 1, msg: '后端出错了'});
		}
		if (doc) {
			return res.json({code: 0,data: doc});
		}
	})
	// 用户有没有cookie
	
})

Router.get('/get_chat_list', function(req, res) {
	const userid = req.cookies.userid; 
	//Chat.remove({}, function(err, doc){});
	User.find({}, function(err, userdoc){
		let users = {};
		userdoc.forEach((u) => {
			users[u._id] = {name: u.user, avatar: u.avatar}
		});
		Chat.find({'$or': [{from: userid}, {to: userid}]}, function(err, doc) {
			if (err) {
				return res,json({
					code: 1,
					msg: '获取消息失败'
				})
			}
			return res.json({
				code: 0,
				msgs: doc,
				users: users
			})
		})
	})	
})

Router.post('/readmsg', function(req, res) {
	const userid = req.cookies.userid;
	const { from } = req.body;
	Chat.updateMany(
		{from, to: userid},
		{'$set': {read: true}},
		{'multi': true},
		function(err, doc) {
		if(!err) {
			return res.json({
				code: 0,
				num: doc.nModified
			})
		}
		return res.json({
			code: 1,
			msg: '修改失败'
		})
	})
});

module.exports = Router;